package part10volatile;


/*
 * 验证volatile可见性
 * */
public class VolatileTest01 {

    private volatile boolean flag = false;

    public void toggleFlag() {
        flag = !flag;
    }

    public boolean isFlag() {
        return flag;
    }

    public static void main(String[] args) {
        VolatileTest01 example = new VolatileTest01();

        // 线程1：持续读取 flag 的值
        Thread thread1 = new Thread(() -> {
            while (!example.isFlag()) {
                // 空循环
            }
            System.out.println("Flag is true");
        });

        // 线程2：修改 flag 的值
        Thread thread2 = new Thread(() -> {
            example.toggleFlag();
            System.out.println("Flag has been toggled");
        });

        // 启动线程
        thread1.start();
        thread2.start();

    }

}
